// 用户相关接口
import axios from 'axios'
import {LOGIN_API, VERIFY_API, REGISTER_API} from "./config";

// 异步延时器
const timer = (ms) => new Promise((resolve) => {
    setTimeout(resolve, ms)
})

export async function register(userInfo) {
    let resp = await axios.post(REGISTER_API, userInfo);
    return resp.data;
}

/**
 * 登录
 * @param username
 * @param password
 * @returns {Promise<any>}
 */
export async function login(userInfo) {
    await timer(1500)

    let resp = await axios.post(LOGIN_API, userInfo);
    let token = resp.data.data.token;
    if (token) {
        localStorage.setItem('_token', token);
    }
    return resp.data;
}

/**
 * 验证登录，获取用户信息
 * @returns {Promise<null|any>}
 */
export async function verifyLogin() {
    // 延时验证
    await timer(2000)

    let token = localStorage.getItem('_token');
    if (!token) {
        return null;
    }
    let resp = await axios.get(VERIFY_API, {
        headers: {
            token
        }
    })
    return resp.data;
}

/**
 * 注销登录
 */
export function logout() {
    localStorage.removeItem('_token');
}

